package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.*;
import com.atguigu.result.Result;
import com.atguigu.service.*;
import com.atguigu.vo.HouseQueryVo;
import com.atguigu.vo.HouseVo;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/house")
public class HouseController {

    @Reference
    private HouseService houseService;

    @Reference
    private CommunityService communityService;

    @Reference
    private HouseBrokerService houseBrokerService;

    @Reference
    private HouseImageService houseImageService;

    @Reference
    private UserFollowService userFollowService;

    @RequestMapping("/list/{pageNum}/{pageSize}")
    public Result<PageInfo<HouseVo>> list(@PathVariable int pageNum, @PathVariable int pageSize,
                       @RequestBody HouseQueryVo houseQueryVo){
        PageInfo<HouseVo> pageInfo = this.houseService.findListPage(pageNum,pageSize,houseQueryVo);
        return Result.ok(pageInfo);
    }

    @RequestMapping("/info/{id}")
    public Result showInfo(@PathVariable Long id, HttpServletRequest request){

        Map<String,Object> map = new HashMap<>();
        //获取指定编号的房屋house信息
        House house = this.houseService.getById(id);
        map.put("house",house);
        //获取该房屋的小区信息
        Community community = this.communityService.getById(house.getCommunityId());
        map.put("community",community);
        //获取该房屋的经纪人信息
        List<HouseBroker> houseBrokerList = this.houseBrokerService.findListByHouseId(id);
        map.put("houseBrokerList",houseBrokerList);
        //获取该房屋的房源图片信息
        List<HouseImage> houseImage1List = this.houseImageService.findList(id, 1);
        map.put("houseImage1List",houseImage1List);
        //获取该房屋是否已经被当前用户关注
        boolean isFollow = false;
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("USER");
        if(userInfo!=null){
            Long userId = userInfo.getId();
            boolean  flag = this.userFollowService.isFollowed(userId,id);
            if(flag){ //当前用户关注了当前房源
                isFollow = true;
            }
        }
        map.put("isFollow",isFollow);

        return Result.ok(map);
    }
}
